<template>
  <div class="home-wrap">
    <div class="tool-wrap">
      <el-button>刷新</el-button>
      <el-button type="primary" @click="handleAddTask">添加任务</el-button>
    </div>
    <div class="task-wrap">
      <el-card>
        <el-table :data="taskList" stripe style="width: 100%">
          <el-table-column prop="id" label="id" width="80"/>
          <el-table-column prop="taskId" label="任务id"/>
          <el-table-column prop="taskName" label="任务名称" />
          <el-table-column prop="taskGroup" label="任务组" />
          <el-table-column label="任务状态">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.taskStatus == 1">运行</el-tag>
              <el-tag type="danger" v-if="scope.row.taskStatus == 2">停止</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="taskType" label="任务类型">
            <template #default="scope">
              <span v-if="scope.row.taskType == 'repeat'">重复执行</span>
              <span v-if="scope.row.taskType == 'onetime'">运行一次</span>
            </template>
          </el-table-column>
          <el-table-column prop="subType" label="订阅类型">
            <template #default="scope">
              <span v-if="scope.row.subType == 'EXCLUSIVE'">独占</span>
              <span v-if="scope.row.subType == 'SHARED'">共享</span>
            </template>
          </el-table-column>
          <el-table-column prop="cronExpr" label="cron表达式" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="updateTime" label="更新时间" />
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button v-if="scope.row.taskStatus == 1" type="warning" size="small" @click="handleStatus(scope.row.taskId, 2)">
                去停止
              </el-button>
              <el-button v-if="scope.row.taskStatus == 2" type="success" size="small" @click="handleStatus(scope.row.taskId, 1)">
                去运行
              </el-button>
              <el-button type="info" size="small" @click="handleParam(scope.row)">
                参数
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.taskId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-dialog
        v-model="addTaskFlag"
        title="添加任务"
        :width="500"
    >
      <el-form :model="addForm" :label-position="labelPosition" label-width="auto">
        <el-form-item label="任务名称" required >
          <el-input v-model="addForm.taskName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="任务组" required >
          <el-input v-model="addForm.taskGroup" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="任务类型" required >
          <el-select v-model="addForm.taskType" placeholder="Select">
            <el-option label="重复执行" value="repeat"/>
            <el-option label="运行一次" value="onetime"/>
          </el-select>
        </el-form-item>
        <el-form-item label="订阅类型" required >
          <el-select v-model="addForm.subType" placeholder="Select">
            <el-option label="独占" value="EXCLUSIVE"/>
            <el-option label="共享" value="SHARED"/>
          </el-select>
        </el-form-item>
        <el-form-item label="cron表达式" required >
          <el-input v-model="addForm.cronExpr" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="任务参数">
          <el-input
            v-model="addForm.taskData"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea" 
          />
        </el-form-item>
        <el-form-item label="任务扩展参数">
          <el-input
            v-model="addForm.taskExtendParam"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" @click="handleExecTask">立即执行</el-button>
          <el-button @click="addTaskFlag = false">取 消</el-button>
          <el-button type="primary" @click="handleAddTaskConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="paramFlag"
        title="查看任务参数"
        :width="500"
    >
      <el-form :model="tempTask" :label-position="labelPosition" label-width="auto">
        <el-form-item label="任务参数">
          <el-input
            v-model="tempTask.taskData"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            readonly 
          />
        </el-form-item>
        <el-form-item label="任务扩展参数">
          <el-input
            v-model="tempTask.taskExtendParam"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            readonly 
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from "vue";
import { getTimeTastList, TimeTask, updateTaskStatus, addTaskData, addTask, deleteTask, execTaskTest } from "@/api/TaskApi.ts"
import { ElMessage, ElMessageBox, ElLoading, FormProps } from 'element-plus'

const addTaskFlag = ref<boolean>(false)
const addForm = ref<addTaskData>({
    taskName: '',
    taskGroup: '',
    taskStatus:0,
    taskType:'',
    cronExpr:'',
    subType:'',
    taskData:'',
    taskExtendParam:''
  })
const labelPosition = ref<FormProps['labelPosition']>('top')
const tempTask = ref<TimeTask>({
  id:0,
  taskId:'',
  taskName:'',
  taskGroup:'',
  taskStatus:0,
  taskType:'',
  cronExpr:'',
  subType:'',
  taskData:'',
  taskExtendParam:'',
  updateTime:'',
  createTime:''
})
const paramFlag = ref<boolean>(false)
const taskList = ref<Array<TimeTask>>()
const handleTaskList = async () => {
  const loading = getLoading('数据加载中...')
  let rs = await getTimeTastList()
  loading.close()
  taskList.value = rs.data ? rs.data : []
}

const getLoading = (msg:string):any  =>{
  return ElLoading.service({
    lock: true,
    text: msg,
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

onMounted(() => {
  handleTaskList()
})


const handleDelete = (taskId: string) => {
  ElMessageBox.confirm('是否要删除任务？', '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  ).then(async () => {
    let rs = await deleteTask(taskId)
    if(rs.code !== '200'){
      ElMessage.error('删除失败')
      return
    }
    await handleTaskList()
  }).catch(() => {})
}

const handleStatus = async (taskId:string, status:number) => {
  let rs = await updateTaskStatus(taskId, status)
  if(rs.code == '200'){
    ElMessage.success('修改成功')
    await handleTaskList()
  }
}

const handleParam = (row: TimeTask) => {
  tempTask.value = row
  paramFlag.value = true
}

const handleAddTask = () => {
  addForm.value = {
    taskName: '',
    taskGroup: '',
    taskStatus:0,
    taskType:'',
    cronExpr:'',
    subType:'',
    taskData:'',
    taskExtendParam:''
  }
  addTaskFlag.value = true
}

const handleAddTaskConfirm = async () => {
  if (!addForm.value) {
    return
  }
  let rs = await addTask(addForm.value)
  if(rs.code === '200'){
    await handleTaskList()
    addTaskFlag.value = false
  }
}

const handleExecTask = async () => {
  if (!addForm.value) {
    return
  }
  let rs = await execTaskTest(addForm.value)
  if (rs.code === '200') {
    ElMessage.success('执行成功')
  }
}
</script>

<style lang="less" scoped>
.home-wrap{
  padding: 20px;

  .tool-wrap{
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
  }

  .task-wrap{
    margin-top: 20px;
  }
}
</style>